import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../../common/api/index.dart';
import '../../../../../common/models/index.dart';
import '../../../../../common/style/index.dart';
import '../../../../../common/utils/index.dart';
import '../../../../../common/values/index.dart';
import '../../../../../common/widgets/index.dart';
import '../index.dart';

///
/// 消息体 UI
///
class MsgBodyWidget extends GetView<ImChatController> {
  final IMMessageBody msgBody;
  final bool isSender;
  final String msgId;
  const MsgBodyWidget({
    Key? key,
    required this.msgBody,
    required this.isSender,
    required this.msgId,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var padding = EdgeInsets.zero;
    if (isSender) {
      padding = const EdgeInsets.only(right: 10);
    } else {
      padding = const EdgeInsets.only(left: 10);
    }
    switch (msgBody.type) {
      case "text":
        return textBodyView(msgBody.body ?? '');
      case "emoji":
        return Padding(
            padding: padding,
            child: Image.asset(
              O2Emoji.getEmojiPath(msgBody.body!),
              width: 32,
              height: 32,
            ));
      case "image":
        // 本地图片
        if (msgBody.fileTempPath != null && msgBody.fileTempPath!.isNotEmpty) {
          return Padding(
              padding: padding,
              child: Image.file(File(msgBody.fileTempPath!),
                  width: 144, height: 192));
        }
        var imageUrl =
            MessageCommunicationService.to.getIMMsgImageUrl(msgBody.fileId!);
        return Padding(
            padding: padding,
            child: Image.network(imageUrl,
                headers: controller.headers, width: 144, height: 192));
      case "audio":
        return voiceBodyView(isSender);
      case "location":
        return Padding(
            padding: padding, child: locationMsgView(msgBody.address ?? ''));
      case "file":
        return Padding(padding: padding, child: fileMsgView(context, msgBody, isSender));
      case "process":
        return processMsgView(context);
      case "cms":
        return textBodyView('文档');
      case "messageHistory":
        return messageHistoryView(context);
    }
    return Container();
  }

  Widget textBodyView(String text) {
    return Text(
      HtmlUtils.contentEscapeBackToSymbol(text),
      style: TextStyle(
          color: isSender ? Colors.white : Colors.black, fontSize: 14),
    );
  }

  // 音频播放
  Widget voiceBodyView(bool isSender) {
    return SoundMessageView(msgId, msgBody.audioDuration ?? '', isSender);
  }

  ///
  /// 位置消息
  Widget locationMsgView(String address) {
    return SizedBox(
      width: 175,
      height: 109,
      child: Stack(children: [
        const Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            top: 0,
            child: AssetsImageView('chat_location_background.png')),
        Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              height: 32,
              color: AppColor.whiteTransparentBackground,
              alignment: Alignment.center,
              child: Text(
                address,
                softWrap: true,
                textAlign: TextAlign.center,
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                style: const TextStyle(color: AppColor.primaryText),
              ),
            ))
      ]),
    );
  }

  Widget fileMsgView(BuildContext context, IMMessageBody body, bool isSender) {
    String fileIcon =
        FileIcon.getFileIconAssetsNameByExtension(body.fileExtension ?? '');
    List<Widget> list;
    if (isSender) {
      list = [
        Expanded(
            flex: 1,
            child: Text(
              body.fileName ?? '',
              softWrap: true,
              textAlign: TextAlign.end,
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            )),
        const SizedBox(width: 5),
        AssetsImageView(fileIcon, width: 40, height: 40),
        const SizedBox(width: 5)
      ];
    } else {
      list = [
        const SizedBox(width: 5),
        AssetsImageView(fileIcon, width: 40, height: 40),
        const SizedBox(width: 5),
        Expanded(
            flex: 1,
            child: Text(
              body.fileName ?? '',
              softWrap: true,
              textAlign: TextAlign.start,
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ))
      ];
    }
    return Container(
        width: 175,
        height: 70,
        decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(10)),
            color: Theme.of(context).colorScheme.background),
        child: Row(
          mainAxisAlignment:
              isSender ? MainAxisAlignment.end : MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: list,
        ));
  }

  Widget processMsgView(BuildContext context) {
    controller.getProcessAppIcon(msgBody.application); // 下载
    return Container(
        width: 200,
        decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(10)),
            color: Theme.of(context).colorScheme.background),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
                padding: const EdgeInsets.only(top: 10),
                child: Text('【${msgBody.processName ?? ''}】',
                    style: Theme.of(context).textTheme.bodyMedium)),
            Padding(
                padding: const EdgeInsets.only(top: 10, bottom: 10, left: 10),
                child: Text(msgBody.title ?? '无标题',
                    style: Theme.of(context).textTheme.bodyLarge)),
            const Divider(
              height: 1,
            ),
            Padding(
                padding: const EdgeInsets.only(top: 10, bottom: 10, left: 5),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const SizedBox(width: 5),
                    Obx(() => controller.state
                                .processAppIconMap[msgBody.application!] ==
                            null
                        ? const Icon(Icons.image, size: 22)
                        : Image.memory(
                            controller
                                .state.processAppIconMap[msgBody.application!]!,
                            width: 22,
                            height: 22,
                            fit: BoxFit.cover,
                          )),
                    const SizedBox(width: 10),
                    Text('${msgBody.applicationName}',
                        style: Theme.of(context).textTheme.bodySmall),
                  ],
                )),
          ],
        ));
  }

  Widget messageHistoryView(BuildContext context) {
    return Container(
        width: 200,
        decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(4)),
            color: Theme.of(context).colorScheme.background),
        padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 8),
        child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(msgBody.messageHistoryTitle?? '',
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(color: AppColor.primaryText),
                      maxLines: 2,
                      textAlign: TextAlign.start,
                      overflow: TextOverflow.ellipsis),
                  const SizedBox(height: 10),
                  Text(msgBody.messageHistoryDesc ?? '',
                      style: Theme.of(context)
                          .textTheme
                          .bodySmall
                          ?.copyWith(color: AppColor.secondaryText), maxLines: 4, overflow: TextOverflow.ellipsis),
                  const SizedBox(height: 5),
                  const Divider(height: 1),
                  const SizedBox(height: 5),
                  Text('im_chat_msg_forward_tag'.tr,
                      style: Theme.of(context)
                          .textTheme
                          .bodySmall
                          ?.copyWith(color: AppColor.secondaryText)),
                ],
              ));
  }
}



class SoundMessageView extends StatefulWidget {
  const SoundMessageView(this.msgId, this.audioDuration, this.isSender,
      {super.key});
  final String msgId;
  final bool isSender;
  final String audioDuration;

  @override
  State<SoundMessageView> createState() => _SoundMessageViewState();
}

class _SoundMessageViewState extends State<SoundMessageView> {
  bool isPlaying = false;
  final _event = EventBus();

  @override
  void initState() {
    _event.on(EventBus.imSoundMessagePlayMsg, '_SoundMessageViewState', (arg) {
      if (arg == widget.msgId) {
        setState(() {
          isPlaying = true;
        });
      }
    });
    _event.on(EventBus.imSoundMessageStopPlayMsg, '_SoundMessageViewState',
        (arg) {
      setState(() {
        isPlaying = false;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Expanded(
            flex: 1,
            child: Text(
               '${widget.audioDuration} "',
              style: Theme.of(context)
                  .textTheme
                  .bodyMedium
                  ?.copyWith(color: AppColor.primaryText),
            )),
        Visibility(
          visible: isPlaying,
          replacement: Image(
            image: AssetImage(widget.isSender
                ? 'assets/images/chat_play_right_s.png'
                : 'assets/images/chat_play_left_s.png'),
            width: 32,
            height: 32,
          ),
          child: Image.asset(
            widget.isSender
                ? 'assets/gif/chat_play_right.gif'
                : 'assets/gif/chat_play_left.gif',
            width: 32,
            height: 32,
          ),
        )
      ],
    );
  }
}